package com.ftar.urgent.ui;

import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ftar.urgent.R;
import com.ftar.urgent.adapter.AllItemAdapter;
import com.ftar.urgent.api.resp.ItemRecordsVo;
import com.ftar.urgent.constant.ArouterConstant;
import com.ftar.urgent.databinding.ActivityAllItemBinding;
import com.ftar.urgent.databinding.ActivityAllitemCommaBinding;
import com.ftar.urgent.viewmodel.AllItemActivityModel;
import com.ftar.urgent.viewmodel.CommonEvent;
import com.ftar.urgent.viewmodel.SP_Constants;
import com.ftar.urgent.voice.OffLineVoiceCmd;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

@Route(path = ArouterConstant.ALL_ITEM_ACTIVITY)
public class AllItemActivity extends BaseActivity {

    private AllItemAdapter allItemAdapter;
    private ActivityAllItemBinding mBinding;
    private ActivityAllitemCommaBinding mCommaBinding;
    private AllItemActivityModel mModel;
    private SoundPool soundPool;
    private int soundId;
    @Autowired
    public int currentId;
    @Autowired
    public int currentCode;
    @Autowired
    public int parentId;
    @Autowired
    public int parentCode;

    @Override
    protected ViewDataBinding getChildBinding() {
        mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_all_item, null, false);
        mCommaBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_allitem_comma, null, false);
        mRootBind.customCommand.addView(mCommaBinding.getRoot());
        mBinding.setHandler(this);
        return mBinding;
    }

    @Override
    protected String voiceHint() {
        int size = 0;
        if (allItemAdapter != null) {
            size = allItemAdapter.getCount();
        }
        int pageSize = 0;
        if (mModel != null) {
            pageSize = mModel.getPageSize();
        }
        if (size > pageSize) {
            return "打开第1/2/3/4/5/6个";
        } else if (size == 0) {
            return "无数据";
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append("打开第");
            for (int i = 1; i <= size; i++) {
                sb.append(i).append("/");
            }
            String substring = sb.substring(0, sb.length() - 1);
            return substring + "个";
        }
    }

    private void tipsVoiceInit() {
        SoundPool.Builder spb = new SoundPool.Builder();
        spb.setMaxStreams(10);
        soundPool = spb.build();
        soundId = soundPool.load(this, R.raw.tips, 1);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        mBinding.setLifecycleOwner(this);
        init();
        tipsVoiceInit();
        observe();
    }


    private void observe() {
        mModel.mRootList.observe(mBinding.getLifecycleOwner(), new Observer<List<ItemRecordsVo>>() {
            @Override
            public void onChanged(List<ItemRecordsVo> v) {
                allItemAdapter.refreshList(v);
                setVoiceHint();
            }
        });


        mModel.anXinData.observe(mBinding.getLifecycleOwner(), new Observer<List<ItemRecordsVo>>() {
            @Override
            public void onChanged(List<ItemRecordsVo> vo) {
                if (vo != null && vo.size() > 0) {
                    mModel.setStep(AllItemActivityModel.STEP_DETAIL);
                    soundPool.play(soundId, 1, 1, 0, 0, 1);
                } else {
                    // 空数据
                    mModel.setStep(AllItemActivityModel.STEP_RESULT_EMPTY);
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long selectedId = allItemAdapter.getmSelectedId();
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (mModel.getStep() == AllItemActivityModel.STEP_INDEX) {
                    // 第一个 且 前面还有页
                    if (selectedId == 0 && mModel.getCurrentPage() != 1) {
                        setItemSelected(mModel.getPageSize() - 1);
                        mModel.goPreviousPage();
                        break;
                    }
                    if (selectedId > 0) {
                        selectedId -= 1;
                    }
                    setItemSelected((int) selectedId);
                } else if (mModel.getStep() == AllItemActivityModel.STEP_DETAIL) {
                    mModel.goResultPreviousPage();
                }
                break;

            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (mModel.getStep() == AllItemActivityModel.STEP_INDEX) {
                    // 最后一个 且 后面还有页
                    if (selectedId == allItemAdapter.getCount() - 1 && mModel.getCurrentPage() < mModel.getTotalPage()) {
                        setItemSelected(0);
                        mModel.goNextPage();
                        break;
                    }
                    if (selectedId < allItemAdapter.getCount() - 1) {
                        selectedId += 1;
                    }
                    setItemSelected((int) selectedId);
                } else if (mModel.getStep() == AllItemActivityModel.STEP_DETAIL) {
                    mModel.goResultNextPage();
                }
                break;
            case KeyEvent.KEYCODE_F9:
                if (mModel.getStep() == AllItemActivityModel.STEP_INDEX) {
                    itemClick(Long.valueOf(selectedId).intValue());
                } else if (mModel.getStep() == AllItemActivityModel.STEP_DETAIL) {
                    mModel.setStep(AllItemActivityModel.STEP_DETAIL_MORE);
                } else if (mModel.getStep() == AllItemActivityModel.STEP_DETAIL_MORE) {
                    mModel.setStep(AllItemActivityModel.STEP_DETAIL);
                }
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            onKeyDown(event.getKeyCode(), event);
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCommonEvent(CommonEvent event) {
        if (!event.getmClass().equals(this.getClass().getName())) {
            return;
        }
        switch (event.getMsg()) {
            case SP_Constants.EVENT_COMMAND_ASR:
                String command = event.getData();
                onAsrCommand(command);
                break;
            default:
                break;
        }
    }

    private void setItemSelected(int pos) {
        mBinding.allItemGridview.setSelection(pos);
        allItemAdapter.setSelectItem(pos);
    }

    private void onAsrCommand(String command) {
        if (!isActivityVisible()) {
            return;
        }
        switch (command) {
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_1:
                goItem(1);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_2:
                goItem(2);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_3:
                goItem(3);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_4:
                goItem(4);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_5:
                goItem(5);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_6:
                goItem(6);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_7:
                goItem(7);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_8:
                goItem(8);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_9:
                goItem(9);
                break;

            case OffLineVoiceCmd.OfflineVoice.GLOBAL_PAGE_PRE:
                //上一页
                if (mBinding.allItemGridview.getVisibility() == View.VISIBLE) {
                    mModel.goPreviousPage();
                } else {
                    mModel.goResultPreviousPage();
                }
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_PAGE_NEXT:
                //下一页
                if (mModel.getStep() == AllItemActivityModel.STEP_INDEX) {
                    mModel.goNextPage();
                } else if (mModel.getStep() == AllItemActivityModel.STEP_DETAIL) {
                    mModel.goResultNextPage();
                }
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_MORE:
                mModel.setStep(AllItemActivityModel.STEP_DETAIL_MORE);
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_BACK:
                // 返回
                if (mModel.getStep() == AllItemActivityModel.STEP_INDEX) {
                    backPage();
                } else if (mModel.getStep() == AllItemActivityModel.STEP_DETAIL) {
                    mModel.setStep(AllItemActivityModel.STEP_INDEX);
                } else if (mModel.getStep() == AllItemActivityModel.STEP_DETAIL_MORE) {
                    mModel.setStep(AllItemActivityModel.STEP_DETAIL);
                }
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_END:
            case OffLineVoiceCmd.OfflineVoice.CHECK_END:
                mModel.resetResultPageInfo();
                mModel.setStep(AllItemActivityModel.STEP_INDEX);
                break;
        }

    }

    private void goItem(int pos) {
        final int focusPos = pos - 1;
        setItemSelected(focusPos);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                itemClick(focusPos);
            }
        }, 500);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void init() {
        mModel = new AllItemActivityModel(this, mBinding, mRootBind, mCommaBinding);
        allItemAdapter = new AllItemAdapter(mBinding.getHandler(), mModel.getmRootList());
        mBinding.allItemGridview.setAdapter(allItemAdapter);
        mBinding.allItemGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                itemClick(position);
            }
        });
        mModel.setStep(AllItemActivityModel.STEP_INDEX);
        mModel.initAllItemData();
    }

    private void itemClick(int pos) {
        List<ItemRecordsVo> itemRecordsVos = mModel.getmRootList();
        if (itemRecordsVos != null && !itemRecordsVos.isEmpty()) {
            ItemRecordsVo vo = itemRecordsVos.get(pos);
            mBinding.resultTitle.setText(vo.getProject());
            mModel.sendToAnXin(vo.getProject());
        }
    }

    /**
     * 返回上一层
     */
    private void backPage() {
        this.finish();
    }
}